<template>
  <div class="class-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>班级管理</span>
          <el-button type="primary" @click="handleAdd" v-if="userStore.userInfo?.roleCode && ['admin', 'teacher'].includes(userStore.userInfo.roleCode)">
            <el-icon><Plus /></el-icon>
            新增班级
          </el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" :model="queryForm" class="search-form">
        <el-form-item label="关键词">
          <el-input
            v-model="queryForm.keyword"
            placeholder="班级名称/编码"
            clearable
            @clear="handleQuery"
          />
        </el-form-item>
        <el-form-item label="所属院系">
          <el-select
            v-model="queryForm.deptId"
            placeholder="请选择院系"
            clearable
            @clear="handleQuery"
          >
            <el-option
              v-for="dept in deptList"
              :key="dept.id"
              :label="dept.deptName"
              :value="dept.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table
        :data="tableData"
        v-loading="loading"
        style="width: 100%"
        border
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="classCode" label="班级编码" width="150" />
        <el-table-column prop="className" label="班级名称" min-width="150" />
        <el-table-column prop="deptName" label="所属院系" width="150" />
        <el-table-column prop="enrollYear" label="入学年份" width="120" align="center" />
        <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="180" fixed="right" v-if="userStore.userInfo?.roleCode && ['admin', 'teacher'].includes(userStore.userInfo.roleCode)">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button link type="danger" size="small" @click="handleDelete(row)" v-if="userStore.userInfo?.roleCode === 'admin'">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryForm.current"
          v-model:page-size="queryForm.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleQuery"
          @current-change="handleQuery"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="650px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="90px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="班级编码" prop="classCode">
              <el-input 
                v-model="form.classCode" 
                placeholder="如：2024CS01"
                clearable
                :disabled="!!form.id"
              >
                <template #prefix>
                  <el-icon><Postcard /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班级名称" prop="className">
              <el-input 
                v-model="form.className" 
                placeholder="如：计科1班"
                clearable
              >
                <template #prefix>
                  <el-icon><School /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属院系" prop="deptId">
              <el-select 
                v-model="form.deptId" 
                placeholder="请选择院系" 
                style="width: 100%"
                clearable
                filterable
              >
                <template #prefix>
                  <el-icon><OfficeBuilding /></el-icon>
                </template>
                <el-option
                  v-for="dept in deptList"
                  :key="dept.id"
                  :label="dept.deptName"
                  :value="dept.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入学年份" prop="enrollYear">
              <el-date-picker
                v-model="form.enrollYear"
                type="year"
                placeholder="选择入学年份"
                style="width: 100%"
                value-format="YYYY"
              >
                <template #prefix>
                  <el-icon><Calendar /></el-icon>
                </template>
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息（选填）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" size="large">
            <el-icon><Close /></el-icon>
            取消
          </el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading" size="large">
            <el-icon><Check /></el-icon>
            {{ form.id ? '保存' : '确定' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Search, Refresh, School, OfficeBuilding, Postcard, Calendar, Check, Close } from '@element-plus/icons-vue'
import { getClassPage, addClass, updateClass, deleteClass } from '@/api/class'
import { getDeptList } from '@/api/dept'
import { useUserStore } from '@/store/user'
import type { Classes, Dept } from '@/types'

const userStore = useUserStore()

// 查询表单
const queryForm = reactive({
  current: 1,
  size: 10,
  keyword: '',
  deptId: undefined as number | undefined
})

// 表格数据
const tableData = ref<Classes[]>([])
const total = ref(0)
const loading = ref(false)

// 院系列表
const deptList = ref<Dept[]>([])

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('新增班级')
const formRef = ref<FormInstance>()
const submitLoading = ref(false)

// 表单数据
const form = reactive<Classes>({
  classCode: '',
  className: '',
  deptId: 0,
  enrollYear: undefined,
  remark: ''
})

// 表单验证规则
const rules: FormRules = {
  classCode: [
    { required: true, message: '请输入班级编码', trigger: 'blur' },
    { min: 2, max: 30, message: '编码长度在 2 到 30 个字符', trigger: 'blur' }
  ],
  className: [
    { required: true, message: '请输入班级名称', trigger: 'blur' },
    { min: 2, max: 50, message: '名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  deptId: [
    { required: true, message: '请选择所属院系', trigger: 'change' }
  ]
}

// 获取院系列表
const getDepts = async () => {
  try {
    const data = await getDeptList()
    deptList.value = data
  } catch (error) {
    console.error('获取院系列表失败', error)
  }
}

// 查询列表
const getList = async () => {
  loading.value = true
  try {
    const data = await getClassPage(queryForm)
    tableData.value = data.records.map(item => {
      const dept = deptList.value.find(d => d.id === item.deptId)
      return {
        ...item,
        deptName: dept?.deptName || ''
      }
    })
    total.value = data.total
  } catch (error) {
    console.error('获取班级列表失败', error)
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  queryForm.current = 1
  getList()
}

// 重置
const handleReset = () => {
  queryForm.keyword = ''
  queryForm.deptId = undefined
  handleQuery()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增班级'
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: Classes) => {
  dialogTitle.value = '编辑班级'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row: Classes) => {
  try {
    await ElMessageBox.confirm('确定要删除该班级吗？', '提示', {
      type: 'warning'
    })
    await deleteClass(row.id!)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败', error)
    }
  }
}

// 提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (form.id) {
          await updateClass(form)
          ElMessage.success('更新成功')
        } else {
          await addClass(form)
          ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        getList()
      } catch (error) {
        console.error('提交失败', error)
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 对话框关闭
const handleDialogClose = () => {
  formRef.value?.resetFields()
  Object.assign(form, {
    classCode: '',
    className: '',
    deptId: 0,
    enrollYear: undefined,
    remark: ''
  })
  delete form.id
}

onMounted(() => {
  getDepts()
  getList()
})
</script>

<style scoped lang="scss">
.class-container {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .search-form {
    margin-bottom: 20px;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-input__prefix) {
  display: flex;
  align-items: center;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}
</style>

